import redis

class RedisNumpy:
    def __init__(self, ):
        self.conn_redis = redis.StrictRedis(host="localhost",port=6379,db=1,password='9rhy*5eH8$i2rKDobCL^HecWUr&LYGXz2e0GQw93KlcumK9MzDvKFfFX@@ilwlsS7',decode_responses=True, charset='UTF-8', encoding='UTF-8')

    def array_to_bytes(self, array):
        """ numpy数组转换为bytes，传入redis
        :return: encoded bytes
        """
        h, w = array.shape
        shape = struct.pack('>II', h, w)
        encoded = shape + array.tobytes()
        return encoded

    def bytes_to_array(self, bytes):
        """ redis中获取的values转换为numpy
        :return: array
        """
        h, w = struct.unpack('>II', bytes[:8])
        # 注意这里dtype和输入一致，防止数据长度对齐问题
        a = np.frombuffer(bytes[8:], dtype=np.float32).reshape(h, w)
        return a

    def get(self, key):
        """ 获取redis内key对应的数据包
        :param key: room_id
        :return: value(M*N矩阵),key不存在，返回None
        """
        # value = None
        # if self.conn_redis.exists(key):
        value = self.conn_redis.get(key)
        value = self.bytes_to_array(value)
        return value

    def set(self, key, item):
        """  新信息写入redis
        :param key:  ****
        :param item:*****
        """
        b_value = self.array_to_bytes(item)
        self.conn_redis.set(key, b_value)